classSolution(object): deftwoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ # 使用map存储差值和位置。例如: nums = [2, 7, 11, 15], target = 9 # 那么 map 的第一个元素就是 {2:0}, 2 为元素值, 0 为元素位置 # 这样能一次性拿到差值元素的位置 map = {} for i, x in enumerate(nums): chazhi = target - x if chazhi in map: # 找到了 return [map[chazhi], i] else: map[x] = i
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
functwoSum(nums []int, target int) []int { var m = make(map[int]int) var res []int
for i, x := range nums{ chazhi := target - x if _, ok := m[chazhi]; ok{ res = append(res, m[chazhi]) res = append(res, i) return res }else{ m[x] = i } } return res }